import pymysql
from todo import Todo
class TodoStrongMysql:


    @staticmethod
    def get_connection():
        return pymysql.Connection(host='192.168.88.128', database='Todo',user='root',password='root@123ABC',
                                  autocommit= True)
    def init_db(self):
        with self.get_connection() as coon:
            cusor = coon.cursor()
            cusor.execute('''CREATE TABLE IF NOT EXISTS todos(
            todo_id int NOT NULL AUTO_INCREMENT,             
            title VARCHAR(127) NOT NULL DEFAULT(''),
            complete int NOT NULL DEFAULT(0) ,
            PRIMARY KEY (todo_id)
            ''')
    def create(self,title:str):
         with self.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("insert into todos(title) values(%s)",(title,))
            cursor.execute("select last_insert_id()")
            (todo_id,) = cursor.fetchone()
            return Todo(title,id=todo_id)
            # res = cursor.execute("select * from students;")
            # data = cursor.fetchall()
            # print(data)
    def convert_row_to_object(self,row):
        return Todo(row[1],id=row[0],completed=True if row[2]==1 else False)

    def get_list(self):
        with self.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("select * from todos")
            todo_list = cursor.fetchall()
            onject_list = []
            for row in todo_list:
                onject_list.append(self.convert_row_to_object(row))
        return onject_list
    def get_by_id(self,todo_id):
        with self.get_connection() as  coon:
            cursor = coon.cursor()
            cursor.execute("select * from todos where todo_id = %s",(todo_id))
            todo = cursor.fetchone()
            if todo is not None:
                return self.convert_row_to_object(todo)

    def mark_completed(self,todo_id):
        with self.get_connection() as coon:
            cuesor = coon.cursor()
            cuesor.execute("update todos set complete = 1 where todo_id = %s",(todo_id))
            coon.commit()
            return self.get_by_id(todo_id)

    def del_todos(self, todo_id):
        with self.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('select * from todos where todo_id=%s', (todo_id,))
            sar = self.get_by_id(todo_id)
            if sar is not None:
                cursor.execute('delete from todos where todo_id=%s', (todo_id,))
                return sar


manger = TodoStrongMysql()
for i in manger.get_list():
    print(i.__dict__)